<?php
/**
 * Name: BaseController.class.php
 * Description:
 * User: DIY
 * Date: 2016/9/6
 * Time: 18:45
 */

namespace Admin\Controller;

use Common\Model\AdminLogModel;
use Common\Model\AdminUserModel;
use Common\Model\AdminAuthModel;
use Think\Controller;

class BaseController extends Controller{

    protected $admin_user_id;

    public function __construct(){
        parent::__construct();

        //验证用户是否登录
        $this->admin_user_id = check_login();
        if(empty($this->admin_user_id)){
            $this->error('登录已过期',U('Admin/Login/index',2));
        }
        //菜单
        $menu_name = 'admin_menu_'.$this->admin_user_id;
        $menu=S($menu_name); //缓存菜单
        $AdminAuthModel = new AdminAuthModel();
        if(empty($menu)){
            $menu = ($AdminAuthModel->getAdminAuthTreeByAdmin($this->admin_user_id));
            S($menu_name,$menu,array('type'=>'file','expire'=>3600));
        }
        $this->assign('_menu',$menu);
        //权限检测
        $this->checkAdminAuth($AdminAuthModel);

        //记录日志
        //$this->_addLog();
        //管理员信息
        $AdminUserModel = new AdminUserModel();
        $admin_user = $AdminUserModel->getUserByID($this->admin_user_id);
        $this->assign('admin_user',$admin_user);


    }

    /*
     * 验证后台用户权限
     * */
    private function checkAdminAuth(AdminAuthModel $AdminAuthModel){
        //缓存用户权限减少DB操作
        $auth_list = S('auth_list_'.$this->admin_user_id);
        if(empty($auth_list)){
            $auth_list = $AdminAuthModel->getAdminAuthListByAdmin($this->admin_user_id);
            S('auth_list_'.$this->admin_user_id,$auth_list,array('type'=>'file','expire'=>3600));
        }

        //取得当前URL
        $action_url = strtoupper(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME); //转换为大写
        $action_status=0;
        //查找所有节点
        foreach($auth_list as $key => $value){
            if($action_url==strtoupper($value['url'])){
                $action_status=1;
                break;
            }
        }
        if($action_status==0){
            $this->error('您无权限访问...');
        }
    }

    /*
     * 记录所有操作
     * */
    private function _addLog(){
        $AdminLogModel = new AdminLogModel();
        $data = array(
            'route'    => MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME,
            'url'       => $_SERVER['REQUEST_URI'],
            'add_ip'    => get_client_ip(),
            'add_time'  => time(),
            'gets'      => json_encode(I('get.')),
            'posts'     => json_encode(I('post.')),
            'admin_id'  => $this->admin_user_id,
            'user_agent'=> $_SERVER['HTTP_USER_AGENT']
        );
        $AdminLogModel->add($data);

    }
}